Backdrop

프로그래머스 ▸ 코딩테스트 입문

숨어있는 숫자의 덧셈 (2)
0

문제 설명

문자열 my_string이 매개변수로 주어집니다. my_string은 소문자, 대문자, 자연수로만 구성되어있습니다. my_string안의 자연수들의 합을 return하도록 solution 함수를 완성해주세요.

제한사항

  • 1 ≤ my_string의 길이 ≤ 1,000
  • 1 ≤ my_string 안의 자연수 ≤ 1000
  • 연속된 수는 하나의 숫자로 간주합니다.
  • 000123과 같이 0이 선행하는 경우는 없습니다.
  • 문자열에 자연수가 없는 경우 0을 return 해주세요.

입출력 예

my_stringresult
"aAb1B2cC34oOp"37
"1a2b3c4d123Z"133

입출력 예 설명

입출력 예 #1

  • "aAb1B2cC34oOp"안의 자연수는 1, 2, 34 입니다. 따라서 1 + 2 + 34 = 37 을 return합니다.

입출력 예 #2

  • "1a2b3c4d123Z"안의 자연수는 1, 2, 3, 4, 123 입니다. 따라서 1 + 2 + 3 + 4 + 123 = 133 을 return합니다.

풀이

이론

Array.prototype.slice()

slice() 메서드는 어떤 배열의 begin 부터 end 까지(end 미포함)에 대한 얕은 복사본을 새로운 배열 객체로 반환해요. 원본 배열은 바뀌지 않아요.

arr.slice([begin[, end]])
  • begin 또는 end 가 음수인 경우, 배열의 끝에서부터의 길이를 나타내요.
  • begin 이 생략된 경우, 0 번째 인덱스부터 추출해요.
  • end 가 생략된 경우, 배열의 끝까지 추출해요.
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
 
console.log(animals.slice(2));
// Expected output: Array ["camel", "duck", "elephant"]
 
console.log(animals.slice(2, 4));
// Expected output: Array ["camel", "duck"]
 
console.log(animals.slice(1, 5));
// Expected output: Array ["bison", "camel", "duck", "elephant"]
 
console.log(animals.slice(-2));
// Expected output: Array ["duck", "elephant"]
 
console.log(animals.slice(2, -1));
// Expected output: Array ["camel", "duck"]
 
console.log(animals.slice());
// Expected output: Array ["ant", "bison", "camel", "duck", "elephant"]

코드

function solution(my_string) {
  return (
    my_string
      .match(/\d+/g)
      ?.map(Number)
      .reduce((acc, cur) => acc + cur) ?? 0
  );
}